import API from "@/api";
import type { ILessonResult } from "@/pages/lowPricedCourse/trialCourseHome/courseList/index.vue";

export interface IDialogueResult {
  reward_num: number;
  preview: IPreview[];
  dialogue: IDialogue[];
}

export interface IPreview {
  [x: string]: any;
  analysis: string;
  img?: string | null;
  word: string;
  preview_id: number;
  translate: string;
  uk_voice: string;
  us_voice: string;
  us_pron?: string;
  user_voice: string;
  is_comp: number;
  isPlay: boolean;
}

export interface IDialogue {
  analysis: string;
  dialogue_txt_id: number;
  img?: string | null;
  is_comp: number; // 1已上报，0未上报
  sentences: string;
  us_voice: string;
  uk_voice: string;
  user_voice: string;
  is_reward: number; // 0:未获得奖励 1:已获得奖励
}

export interface IDialogueLesson {
  isRelearn: boolean;
  isPreLearn: boolean;
  isNeedLaunchPage: boolean;
  data: {
    questions: IDialogueResult,
    isPreview: boolean;
    currentQuestionIndex: number;
  }
}

export const requestDialogueData = (sectionId: number): Promise<ILessonResult> => {
  return new Promise((resolve, reject) => {
    API.dialogueTxt({ section_id: sectionId })
      .then((res) => {
        let result = res as IDialogueResult;

        let isPreLearn = false; // 是否进入预习页
        let isPreview = true; // 是否是预习
        let isRelearn = false;
        let currentIndex = -1;

        isRelearn = result.dialogue.every((item: IDialogue) => {
          return item.is_comp === 1;
        });

        if (isRelearn) {
          // 清空所有学过的数据，包括预习单词和练习
          result.preview.forEach((item) => {
            item.is_comp = 0;
            item.analysis = "";
          });

          result.dialogue.forEach((item) => {
            item.is_comp = 0;
            item.analysis = "";
          });

          currentIndex = 0;
        } else {
          // 如果存在学习记录，直接跳完最后的学习
          for (let i = 0; i < result.preview.length; i++) {
            if (result.preview[i].is_comp === 0) {
              isPreview = true;
              currentIndex = i;
              break;
            }
          }

          if (currentIndex === -1) {
            for (let i = 0; i < result.dialogue.length; i++) {
              if (result.dialogue[i].is_comp === 0) {
                isPreview = false;
                currentIndex = i;
                break;
              }
            }
          }
        }

        if (currentIndex === 0) {
          isPreLearn = true;
        }

        let data: IDialogueLesson = {
          isRelearn,
          isPreLearn: isRelearn || isPreLearn,
          isNeedLaunchPage: isRelearn || currentIndex === -1, // 重学或新学没记录
          data: {
            questions: result,
            isPreview: isPreview,
            currentQuestionIndex: currentIndex,
          },
        }

        resolve(data);
      })
      .catch(() => {
        reject();
      })
  })
}